import { contextBridge } from 'electron';
import { electronAPI } from '@electron-toolkit/preload';
import { join } from 'path';
import { finder } from '@medv/finder';
// Custom APIs for renderer
const api = {
  addiframe: () => {
    let iframe = document.createElement('iframe');
    iframe.setAttribute('id', 'myiframe');
    iframe.setAttribute(
      'style',
      `
    position:absolute;
    width:500px;
    heigth:30px;
    left:10px;
    top:10px;
    z-index:99999;
    `
    );
    document.body.appendChild(iframe);
    // let pathindex = join(__dirname, '../renderer/view.html');
    // console.log(pathindex);
    iframe.src = 'http://127.0.0.1:5173/view.html';
    window.addEventListener('mousedown', (e) => {
      e.preventDefault();
      const selector = finder(e.target as any);
      console.log(selector);
    });

    window.addEventListener(
      'message',
      (e) => {
        myapi.doal();
      },
      false
    );
  },
};
const myapi = {
  doal: () => {
    let ab = document.querySelectorAll('a').length;
    console.log(ab);
    alert(ab);
  },
};

// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.
if (process.contextIsolated) {
  try {
    contextBridge.exposeInMainWorld('electron', electronAPI);
    contextBridge.exposeInMainWorld('api', api);
    contextBridge.exposeInMainWorld('myapi', myapi);
    document.addEventListener('DOMContentLoaded', api.addiframe);
  } catch (error) {
    console.error(error);
  }
} else {
  // @ts-ignore (define in dts)
  window.electron = electronAPI;
  // @ts-ignore (define in dts)
  window.api = api;
}
